package com.trytech.mongoocrawler.server;

import com.trytech.mongoocrawler.server.transport.handler.CommandProtocolHandler;
import com.trytech.mongoocrawler.server.transport.handler.MonitorProtocolHandler;
import com.trytech.mongoocrawler.server.transport.tcp.NettyTcpServer;
import com.trytech.mongoocrawler.server.xml.CrawlerXmlConfigBean;

/**
 * Created by coliza on 2018/4/30.
 */
public final class LocalCrawlerContext extends CrawlerContext {
    @Override
    protected void doInitSession() {
        //获取url存储在哪里
        for (CrawlerXmlConfigBean crawlerXmlConfigBean : config.getConfigBean().getCrawlers().values()) {
            LocalCrawlerSession initSession = null;
//            CacheXmlConfigBean cacheXmlConfigBean = config.getConfigBean().getCacheXmlConfigBean();
//            String startUrlartUrl = crawlerXmlConfigBean.getStartUrl();
            //注册初始session
//            UrlParserPair urlParserPair = new UrlParserPair(startUrl, crawlerXmlConfigBean.getFirstparser());
            initSession = new LocalCrawlerSession(this, crawlerXmlConfigBean, null);
            crawlerXmlConfigBean.getPipeline().setCrawlerSession(initSession);
            registerSession(initSession);
        }

        for (CrawlerSession session : sessionMap.values()) {
            Thread thread = new Thread((LocalCrawlerSession) session);
            sessionThreadMap.put(session.getSessionId(), thread);
            thread.start();
        }
    }

    @Override
    protected void doInitServer() {
        //启动爬虫server
        crawlerServer = new NettyTcpServer(this, config, config.getConfigBean().getModeConfigBean().getServerPort());
        //初始化ProtocolHandler链
        crawlerServer.addHandler(new CommandProtocolHandler(this));
        crawlerServer.addHandler(new MonitorProtocolHandler(this));
        crawlerServer.start();
    }
}
